1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| import os
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('../MNIST_DATA', one_hot=True)
# 每个批次的大小 batch_size = 100 # 计算一共有多少个批次 n_batch = mnist.train.num_examples // batch_size
# 初始化权值 def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) # 生成一个截断的正态分布 return tf.Variable(initial)
# 初始化偏置 def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial)
# 卷积层 def conv2d(x, W): # x input tensor of shape `[batch, in_height, in_width, in_channels]` 通道数,黑白为1,彩色为3 # W filter / kernel tensor of shape [filter_height, filter_width, in_channels, out_channels] # `strides[0] = strides[3] = 1`. strides[1]代表x方向的步长,strides[2]代表y方向的步长 # padding: A `string` from: `"SAME", "VALID"` same会补0,valid不会补0 return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
# 池化层 def max_pool_2x2(x): # ksize [1,x,y,1] 窗口大小 return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# 定义两个placeholder x = tf.placeholder(tf.float32, [None, 784]) y = tf.placeholder(tf.float32, [None, 10]) # 改变x的格式转为4D的向量[batch, in_height, in_width, in_channels]` x_image = tf.reshape(x, [-1, 28, 28, 1])
|